<template>
  <div class="app-container">
    <!-- 搜索form -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="单据编号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入采购退货申请单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应商" prop="supplierId">
        <el-select
          v-model="queryParams.supplierId"
          clearable
          placeholder="请选择供应商"
        >
          <el-option
            :label="supplier.supName"
            :value="supplier.id"
            v-for="supplier in supplierList"
            :key="supplier.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="单据日期">
        <el-date-picker
          v-model="daterangeOrderDate"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="审批结果" prop="approvalResult">
        <el-select
          v-model="queryParams.approvalResult"
          clearable
          placeholder="请选择"
        >
          <el-option
            :label="approval.name"
            :value="approval.id"
            v-for="approval in approvalList"
            :key="approval.id"
            clearable
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="daterangeCreateDate"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="修改时间">
        <el-date-picker
          v-model="daterangeModifyDate"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 中部按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['caigou:buyBackReq:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['caigou:buyBackReq:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <!-- 中部数据表格 -->
    <el-table
      v-loading="loading"
      :data="buyBackReqList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
        fixed="left"
      />
      <el-table-column label="序号" width="70" align="center" fixed="left">
        <template slot-scope="scope">
          {{
            scope.$index + 1 + (queryParams.pageNum - 1) * queryParams.pageSize
          }}
        </template>
      </el-table-column>
      <el-table-column
        label="单据编号"
        align="center"
        prop="code"
        fixed="left"
        width="200"
      >
        <template slot-scope="scope">
          <el-link type="primary" @click="showBuyBackReq(scope.row)">{{
            scope.row.code
          }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="供应商" align="center" prop="supplier.supName" />
      <el-table-column
        label="采购入库单"
        align="center"
        prop="stockIn.stockInCode"
        width="200"
      >
        <template slot-scope="scope">
          {{ scope.row.stockIn.stockInCode }}
        </template>
      </el-table-column>
      <el-table-column label="退货数量" align="center" prop="allOutStock" />
      <el-table-column
        label="单据日期"
        align="center"
        prop="orderDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="业务员" align="center" prop="srcUser.userName" />
      <el-table-column label="业务部门" align="center" prop="srcDeptName" />
      <el-table-column
        label="审核人"
        align="center"
        prop="approvalUser.userName"
      />
      <el-table-column
        label="审批结果"
        align="center"
        prop="approvalResultName"
        width="120"
      >
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.approvalResult == 2">{{
            scope.row.approvalResultName
          }}</el-tag>
          <el-tag type="danger" v-if="scope.row.approvalResult == 3">{{
            scope.row.approvalResultName
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改人" align="center" prop="modifyBy" />
      <el-table-column
        label="修改时间"
        align="center"
        prop="modifyDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.modifyDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="120"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['caigou:buyBackReq:edit']"
            :disabled="
              scope.row.approvalResult == 2 || scope.row.approvalResult == 3
            "
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['caigou:buyBackReq:remove']"
            :disabled="scope.row.approvalResult != 3"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改采购退货申请单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        :disabled="formDisabled"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="单据编码" prop="code">
              <el-input
                v-model="form.code"
                placeholder="请输入采购退货编码"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供货商" prop="supplierId">
              <el-select
                v-model="form.supplierId"
                clearable
                placeholder="请选择供应商"
                @change="resetDetailList"
              >
                <el-option
                  :label="supplier.supName"
                  :value="supplier.id"
                  v-for="supplier in supplierList"
                  :key="supplier.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="采购入库单" prop="stockInId">
              <el-select
                :value="form.stockInId"
                clearable
                placeholder="请选择采购入库单"
              >
                <el-option
                  :label="form.stockInCode"
                  :value="form.stockInId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-button @click="showStockIn">采购入库单</el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="业务员" prop="srcUserName">
              <el-input
                :value="form.srcUserName"
                placeholder="请选择采购入库单"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="业务部门" prop="srcDeptName">
              <el-input
                :value="form.srcDeptName"
                placeholder="请选择采购入库单"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单据日期" prop="orderDate">
              <el-date-picker
                clearable
                v-model="form.orderDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择单据日期"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <i
          class="el-icon-arrow-down"
          @click="showFormDetail"
          style="cursor: pointer"
        ></i>
        <el-divider></el-divider>
        <div v-show="formDetailDisabled">
          <el-row>
            <el-col :span="8">
              <el-form-item label="审核人" prop="approvalUser.userName">
                <el-input
                  :value="form.approvalUser.userName"
                  disabled
                  placeholder=""
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="审核结果" prop="approvalResultName">
                <el-input
                  :value="form.approvalResultName"
                  disabled
                  placeholder=""
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="审核意见" prop="approvalOption">
                <el-input
                  type="textarea"
                  :value="form.approvalOption"
                  disabled
                  placeholder=""
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="创建人" prop="createBy">
                <el-input :value="form.createBy" placeholder="" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="修改人" prop="modifyBy">
                <el-input :value="form.modifyBy" placeholder="" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="创建时间" prop="createDate">
                <el-date-picker
                  clearable
                  :value="form.createDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  disabled
                  placeholder=""
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="修改时间" prop="modifyDate">
                <el-date-picker
                  clearable
                  :value="form.modifyDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  disabled
                  placeholder=""
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="备注" prop="remark">
                <el-input
                  type="textarea"
                  v-model="form.remark"
                  placeholder=""
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <el-menu
          :default-active="activeIndex"
          class="el-menu-demo"
          mode="horizontal"
          @select="handleDetailSelect"
        >
          <el-menu-item index="1">采购入库明细</el-menu-item>
          <el-menu-item index="2">采购退货明细</el-menu-item>
        </el-menu>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            :disabled="reqSingle"
            @click="handleDetailAdd"
            v-show="activeIndex == '1'"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="orderMultiple"
            @click="handleDetailDelete"
            v-show="activeIndex == '2'"
            >删除</el-button
          >
        </el-col>
        <el-table
          ref="stockInDetailTable"
          :data="stockInDetailList"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleStockInDetailSelectionChange"
          v-show="activeIndex == '1'"
        >
          <el-table-column
            type="selection"
            :selectable="isRowSelectable"
            width="70"
            align="center"
          />
          <el-table-column label="序号" width="70" align="center">
            <template slot-scope="scope">
              {{
                scope.$index +
                1 +
                (queryParams.pageNum - 1) * queryParams.pageSize
              }}
            </template>
          </el-table-column>
          <el-table-column
            prop="proName"
            label="商品"
            width="150"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="houseName"
            label="仓库"
            width="150"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="unitName"
            label="单位"
            width="150"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="num"
            label="入库数量"
            width="150"
            align="center"
          >
          </el-table-column>
          <el-table-column prop="cost" label="单价" width="150" align="center">
          </el-table-column>
          <el-table-column
            prop="passCost"
            label="采购金额"
            width="150"
            align="center"
          >
          </el-table-column>
        </el-table>
        <el-table
          ref="reqTable"
          :data="form.buyBackReqDetailList"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleReqDetailSelectionChange"
          v-show="activeIndex == '2'"
          highlight-current-row
        >
          <el-table-column type="selection" width="70" align="center" />
          <el-table-column label="序号" width="150" align="center">
            <template slot-scope="scope">
              {{
                scope.$index +
                1 +
                (queryParams.pageNum - 1) * queryParams.pageSize
              }}
            </template>
          </el-table-column>
          <el-table-column
            prop="proName"
            label="商品"
            width="150"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="unitName"
            label="单位"
            width="150"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="quantity"
            label="退货数量"
            width="150"
            align="center"
          >
            <template slot-scope="scope">
              <el-form-item prop="quantity" label-width="100">
                <el-input
                  v-model="scope.row.quantity"
                  :min="0"
                  :max="scope.row.stock"
                  @blur="validatequantity(scope.row)"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="cost" label="单价" width="150" align="center">
          </el-table-column>
          <el-table-column
            prop="passCost"
            label="结算金额"
            width="150"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="num"
            label="入库数量"
            width="150"
            align="center"
          >
          </el-table-column>
        </el-table>
      </el-form>
      <!-- 采购入库单内部对话框 -->
      <el-dialog
        width="60%"
        title="选择采购入库单"
        :visible.sync="innerVisible"
        append-to-body
      >
        <!-- 搜索头部 -->
        <el-form
          :model="queryStockInParams"
          ref="queryStockInForm"
          size="small"
          :inline="true"
          v-show="showStockInSearch"
          label-width="68px"
        >
          <el-form-item label="单据编号" prop="orderCode">
            <el-input
              v-model="queryStockInParams.orderCode"
              placeholder="请输入单据编号"
              clearable
              @keyup.enter.native="handleStockInQuery"
            />
          </el-form-item>
          <el-form-item label="创建日期">
            <el-date-picker
              v-model="daterangeStockInCreateDate"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleStockInQuery"
              >搜索</el-button
            >
            <el-button
              icon="el-icon-refresh"
              size="mini"
              @click="resetStockInQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
        <el-table
          ref="stockInTable"
          v-loading="stockInLoading"
          :data="stockInList"
          highlight-current-row
          @current-change="handleCurrentChange"
        >
          <el-table-column label="序号" width="70" align="center">
            <template slot-scope="scope">
              {{
                scope.$index +
                1 +
                (queryStockInParams.pageNum - 1) * queryStockInParams.pageSize
              }}
            </template>
          </el-table-column>
          <el-table-column prop="stockInCode" label="单据编号" width="150">
            <template slot-scope="scope">
              <el-popover
                placement="top-start"
                width="200"
                trigger="hover"
                :content="scope.row.stockInCode"
              >
                <div slot="reference" class="ellipsis-text">
                  {{ scope.row.stockInCode }}
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column prop="createDate" label="创建日期" width="120">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createDate, "{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="typeName" label="出库类型" width="120">
          </el-table-column>
          <el-table-column prop="orderCode" label="源单号" width="120">
          </el-table-column>
          <el-table-column prop="supName" label="供应商" width="120">
          </el-table-column>
          <el-table-column prop="businessDeptName" label="业务部门" width="120">
          </el-table-column>
          <el-table-column prop="businessUserName" label="业务员" width="120">
          </el-table-column>
          <el-table-column prop="passCost" label="结算金额" width="120">
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <pagination
          v-show="stockInTotal > 0"
          :total="stockInTotal"
          :page.sync="queryStockInParams.pageNum"
          :limit.sync="queryStockInParams.pageSize"
          @pagination="getStockInList"
        />
      </el-dialog>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formDisabled"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listBuyBackReq,
  getBuyBackReqById,
  delBuyBackReq,
  addBuyBackReq,
  updateBuyBackReq,
  getBuyBackReqDetailListByBuyBackReqId,
} from "@/api/caigou/buyBackReq";
import { getUser } from "@/api/system/user";
import { listAllSupplies } from "@/api/basedata/supplies";
import { getDept } from "@/api/system/dept";
import { listForBuyBack } from "@/api/store/stockIn";
import { getStockInDetailByStockInId } from "@/api/store/stockInDetail";

export default {
  name: "BuyBackReq",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 采购入库单添加按钮禁用
      reqSingle: true,
      // 采购退货单删除按钮禁用
      orderMultiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购退货申请单表格数据
      buyBackReqList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 业务部门时间范围
      daterangeOrderDate: [],
      // 创建时间范围
      daterangeCreateDate: [],
      // 修改时间范围
      daterangeModifyDate: [],
      // 采购入库明细列表
      stockInDetailList: [],
      // 子表单选择
      activeIndex: "2",
      // 中间数组
      tempDetailList: [],
      // 表单控制
      formDisabled: false,
      // 采购入库列表
      stockInList: [],
      // 仓库列表
      warehouseList: [],
      // 审批结果列表
      approvalList: [
        {
          id: 1,
          name: "未审批",
        },
        {
          id: 2,
          name: "已通过",
        },
        {
          id: 3,
          name: "已驳回",
        },
      ],
      //业务员对象
      srcUser: {},
      // 业务部门对象
      srcDept: {},
      /**  用户内部对话框 */
      userLoading: false,
      deptName: "",
      deptOptions: undefined,
      defaultProps: {
        children: "children",
        label: "label",
      },
      //内部用户对话框
      innerUserVisible: false,
      //内部采购入库单控制
      innerVisible: false,
      // 采购退货申请详细信息
      formDetailDisabled: false,
      // 内部采购入库单搜索参数
      queryStockInParams: {
        pageNum: 1,
        pageSize: 10,
        orderCode: null,
        createDate: null,
        inventoryType: 1,
        status: 1,
        supplierId: null,
      },
      // 内部采购入库创建时间范围
      daterangeStockInCreateDate: [],
      // 内部采购入库单加载状态
      stockInLoading: false,
      // 内部采购入库总数
      stockInTotal: 0,
      // 内部采购入库列表查询表单控制
      showStockInSearch: true,
      // 用户表格数据
      userList: [],
      // 供应商列表
      supplierList: [
        {
          id: 1,
          supName: "供应商1",
        },
        {
          id: 2,
          supName: "供应商2",
        },
        {
          id: 3,
          supName: "供应商3",
        },
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        supplierId: null,
        stockInId: null,
        orderDate: null,
        srcUserId: null,
        approvalResult: null,
        createDate: null,
        modifyDate: null,
      },
      // 表单参数
      // 采购退货明细列表
      form: {
        buyBackReqDetailList: [],
        approvalUser: { userName: "" },
      },
      // 表单校验
      rules: {
        code: [
          {
            required: true,
            message: "采购申请单编号不能为空",
            trigger: "blur",
          },
        ],
        supplierId: [
          {
            required: true,
            message: "供应商不能为空",
            trigger: "blur",
          },
        ],
        stockInId: [
          {
            required: true,
            message: "采购入库单不能为空",
            trigger: "blur",
          },
        ],
        orderDate: [
          { required: true, message: "单据日期不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getSupplierList();
  },
  methods: {
    /**
     * 获取供应商列表
     */
    getSupplierList() {
      listAllSupplies().then((response) => {
        this.supplierList = response.data;
      });
    },

    /**
     * 获取用户列表
     */
    getUserInfo(userId) {
      getUser(userId).then((rs) => {
        this.srcUser = rs.data;
        getDept(this.srcUser.deptId).then((rs) => {
          this.dept = rs.data;
        });
      });
    },

    /**
     * 查询采购退货申请单列表
     */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeOrderDate && "" != this.daterangeOrderDate) {
        this.queryParams.params["beginOrderDate"] = this.daterangeOrderDate[0];
        this.queryParams.params["endOrderDate"] = this.daterangeOrderDate[1];
      }
      if (null != this.daterangeCreateDate && "" != this.daterangeCreateDate) {
        this.queryParams.params["beginCreateDate"] =
          this.daterangeCreateDate[0];
        this.queryParams.params["endCreateDate"] = this.daterangeCreateDate[1];
      }
      if (null != this.daterangeModifyDate && "" != this.daterangeModifyDate) {
        this.queryParams.params["beginModifyDate"] =
          this.daterangeModifyDate[0];
        this.queryParams.params["endModifyDate"] = this.daterangeModifyDate[1];
      }
      listBuyBackReq(this.queryParams).then((response) => {
        this.buyBackReqList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        supplierId: null,
        stockInId: null,
        allOutStock: null,
        orderDate: null,
        srcUserId: null,
        srcDeptId: null,
        approvalId: null,
        approvalResult: null,
        createBy: null,
        createDate: null,
        modifyBy: null,
        modifyDate: null,
        isDel: null,
        buyBackReqDetailList: [],
        approvalUser: { userName: "" },
      };
      this.tempDetailList = [];
      this.stockInDetailList = [];
      this.deleteIds = [];
      this.detailsSelection = [];

      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeOrderDate = [];
      this.daterangeCreateDate = [];
      this.daterangeModifyDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.formDisabled = false;
      this.form.code = "CGTHSQ" + Date.now();
      this.open = true;
      this.title = "添加采购退货申请单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.formDisabled = false;
      this.getBuyBackReq(row);
      this.title = "修改采购退货申请单";
      this.open = true;
    },

    //展示采购退货申请单
    showBuyBackReq(row) {
      this.formDisabled = true;
      this.getBuyBackReq(row);
      this.open = true;
      this.title = "查看采购退货申请单";
    },

    //获取采购退货申请单
    getBuyBackReq(row) {
      const id = row.id || this.ids;
      getBuyBackReqById(id).then(async (response) => {
        this.form = response.data;
        this.form.srcUserName = this.form.srcUser.userName;
        this.form.stockInCode = this.form.stockIn.stockInCode;
        await this.handleCurrentChange(this.form.stockIn);
        getBuyBackReqDetailListByBuyBackReqId(this.form.id).then((response) => {
          this.form.buyBackReqDetailList = response.data;
          this.form.buyBackReqDetailList.forEach((item) => {
            item.proName = item.goods.proName;
            item.unitName = item.goods.unitName;
            this.stockInDetailList.forEach((stockIn) => {
              if (stockIn.goodsId == item.goodsId) {
                item.id = stockIn.id;
                item.passCost = stockIn.passCost;
                item.num = stockIn.num;
                const index = this.stockInDetailList.findIndex(
                  (item) => item.id === stockIn.id
                );
                item.index = index;
                if (index !== -1) this.setRowDisabled(index, true);
              }
            });
          });
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      const isForm = this.checkForm();
      if (isForm) {
        return;
      }
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateBuyBackReq(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBuyBackReq(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除采购退货申请单编号为"' + ids + '"的数据项？')
        .then(function () {
          return delBuyBackReq(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "caigou/buyBackReq/export",
        {
          ...this.queryParams,
        },
        `buyBackReq_${new Date().getTime()}.xlsx`
      );
    },
    // 子表单选择器
    handleDetailSelect(key, keyPath) {
      this.activeIndex = key;
    },
    // 采购退货申请明细多级选择器
    handleReqDetailSelectionChange(val) {
      this.detailsSelection = val;
      this.orderMultiple = !val.length;

      this.deleteIds = val.map((row) => row.id);
    },
    // 采购入库明细多级选择器
    handleStockInDetailSelectionChange(val) {
      this.detailsSelection = val;
      this.reqSingle = !val.length;

      this.tempDetailList = [];
      this.tempDetailList = val.map((row) => {
        const index = this.stockInDetailList.findIndex(
          (item) => item.id === row.id
        );
        return { ...row, index };
      });
    },
    // 子表单新增
    handleDetailAdd() {
      //添加数据，并禁用表单
      this.tempDetailList.forEach((item) => {
        if (
          !this.form.buyBackReqDetailList.some(
            (stockIn) => stockIn.id === item.id
          )
        ) {
          this.form.buyBackReqDetailList.push(item);
        }
        this.setRowDisabled(item.index, true);
      });
      this.clearSelection("stockInDetailTable");
    },
    // 子表单禁用
    isRowSelectable(row) {
      return !row.disabled;
    },
    // 子表单删除
    handleDetailDelete() {
      this.deleteIds.forEach((id) => {
        const index = this.stockInDetailList.findIndex(
          (item) => item.id === id
        );
        if (index !== -1) this.setRowDisabled(index, false);
      });
      this.form.buyBackReqDetailList = this.form.buyBackReqDetailList.filter(
        (item) => !this.deleteIds.includes(item.id)
      );
      this.clearSelection("reqTable");
    },
    // 设置行的禁用状态
    setRowDisabled(index, disabled) {
      if (index !== -1) {
        this.$set(this.stockInDetailList[index], "disabled", disabled);
      }
    },
    // 清空选择状态
    clearSelection(ref) {
      this.$refs[ref].clearSelection();
    },
    // 动态表单校验规则
    validatequantity(row) {
      // 检查是否为数字且非空
      let value = parseFloat(row.quantity);
      const isValidNumber = /^[1-9]\d*$/.test(row.quantity);

      if (!isValidNumber || isNaN(value)) {
        this.$message.error("请输入有效的正数");
        row.quantity = null;
        return;
      }

      // 校验退货数量不能小于0
      if (value < 0) {
        this.$message.error("退货数量不能小于0");
        row.quantity = null;
        return;
      }

      // 校验退货数量不能超过入库数量
      if (value > row.num) {
        this.$message.error("退货数量不能超过入库数量");
        row.quantity = row.num;
      }
    },
    // 表单校验
    checkForm() {
      if (
        !Array.prototype.isPrototypeOf(this.form.buyBackReqDetailList) ||
        this.form.buyBackReqDetailList.length === 0
      ) {
        this.$message.error("请输入采购退货明细");
        return true;
      }
      this.form.buyBackReqDetailList.forEach((item) => {
        if (item.quantity == null) {
          this.$message.error("请输入退货数量");
          return true;
        }
      });
    },

    /**
     * 内部采购入库单弹窗
     */
    //
    //采购入库单弹窗
    showStockIn() {
      if (this.$refs["stockInTable"]) {
        this.$refs["stockInTable"].setCurrentRow();
      }
      this.innerVisible = true;
      this.getStockInList();
    },
    // 关闭内部采购入库单对话框
    cancelInner() {
      this.innerVisible = false;
    },
    /** 查询内部采购入库单列表 */
    getStockInList() {
      this.stockInLoading = true;
      this.queryStockInParams.params = {};
      this.queryStockInParams.supplierId = this.form.supplierId;
      if (
        null != this.daterangeStockInCreateDate &&
        "" != this.daterangeStockInCreateDate
      ) {
        this.queryStockInParams.params["beginCreateDate"] =
          this.daterangeStockInCreateDate[0];
        this.queryStockInParams.params["endCreateDate"] =
          this.daterangeStockInCreateDate[1];
      }
      listForBuyBack(this.queryStockInParams).then((response) => {
        this.stockInList = response.rows;
        this.stockInTotal = response.total;
        this.stockInLoading = false;
      });
    },
    /** 内部采购入库单搜索按钮操作 */
    handleStockInQuery() {
      this.queryStockInParams.pageNum = 1;
      this.getStockInList();
    },
    /** 重置按钮操作 */
    resetStockInQuery() {
      this.daterangeStockInCreateDate = [];
      this.resetForm("queryStockInForm");
      this.handleStockInQuery();
    },
    //内部采购入库单选框选中数据
    async handleCurrentChange(val) {
      this.resetDetailList();
      if (val == null) {
        return;
      }
      this.form.stockInId = val.id;
      this.form.stockInCode = val.stockInCode;
      this.form.supplierId = val.supplierId;
      await getStockInDetailByStockInId(val.id).then((response) => {
        this.stockInDetailList = response.data;
      });
      if (val.businessUserName != null) {
        //业务员名称
        this.form.srcUserName = val.businessUserName;
        //业务部门名称
        this.form.srcDeptName = val.businessDeptName;
        //业务员id
        this.form.srcUserId = val.businessUserId;
      }

      //内部采购入库单控制
      this.innerVisible = false;
    },
    //重置采购入库单和明细
    resetDetailList() {
      this.form.buyBackReqDetailList = [];
      this.tempDetailList = [];
      this.stockInDetailList = [];
      this.form.stockInId = null;
      this.form.stockInCode = null;
    },
    // 显示表单详细信息
    showFormDetail() {
      this.formDetailDisabled = !this.formDetailDisabled;
    },
  },
};
</script>
<style scoped>
/**  长度过长的文本省略号 */
.ellipsis-text {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 120px;
}
</style>
